#!/usr/bin/env python3
"""
模板生视频任务 - 组合流程异步处理
结合图片融合和视频生成的完整流程
"""

from celery import current_app, current_task
from app.celery_app import celery_app
from app.services.ai_manager import ai_service_manager
from app.services.ai_base import GenerationRequest, AIServiceType, AIServiceProvider
import logging
import asyncio
from typing import Dict, Any

logger = logging.getLogger(__name__)

@celery_app.task(bind=True, name='template_to_video_combined')
def generate_template_to_video_async(self, request_data: Dict[Any, Any], user_id: int, params: Dict[str, Any]):
    """
    模板生视频组合任务
    步骤：1. 图片融合 → 2. 图片转视频
    """
    task_id = self.request.id
    logger.info(f"开始执行模板生视频任务 {task_id}")
    
    try:
        # 更新任务状态：开始图片融合
        self.update_state(
            state='PROGRESS',
            meta={
                'progress': 10,
                'message': '开始图片融合...',
                'current_step': '图片融合中',
                'step': 'image_fusion'
            }
        )
        
        # 第一步：图片融合
        logger.info(f"任务 {task_id} - 开始图片融合步骤")
        
        # 构建图片融合请求
        fusion_request = GenerationRequest(
            prompt=params.get("image_prompt", params["video_prompt"]),
            service_type=AIServiceType.IMAGE_GENERATION,
            params={
                "template_image_url": params["template_image_url"],
                "user_image_url": params["user_image_url"], 
                "template_image_base64": params.get("template_image_base64"),
                "user_image_base64": params.get("user_image_base64"),
                "aspect_ratio": params["aspect_ratio"],
                "style": params["style"],
                "fusion_strength": params["fusion_strength"],
                "seed": params["seed"],
                "generation_type": "image_to_image"  # 使用即梦AI支持的类型
            },
            user_id=user_id
        )
        
        # 执行图片融合
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        try:
            # 获取图片生成服务
            image_service = ai_service_manager.get_best_service_for_type(AIServiceType.IMAGE_GENERATION)
            if not image_service:
                raise Exception("没有可用的图片生成服务")
                
            fusion_result = loop.run_until_complete(
                image_service.generate_image(fusion_request)
            )
            
            if not fusion_result.success:
                raise Exception(f"图片融合失败: {fusion_result.error_message}")
                
            intermediate_image_url = fusion_result.result_url
            image_cost = fusion_result.cost or 0.1
            
            logger.info(f"任务 {task_id} - 图片融合完成: {intermediate_image_url}")
            
            # 更新任务状态：图片融合完成，开始视频生成
            self.update_state(
                state='PROGRESS',
                meta={
                    'progress': 50,
                    'message': '图片融合完成，开始视频生成...',
                    'current_step': '视频生成中',
                    'step': 'video_generation',
                    'intermediate_image_url': intermediate_image_url,
                    'image_cost': image_cost
                }
            )
            
            # 第二步：图片转视频
            logger.info(f"任务 {task_id} - 开始视频生成步骤")
            
            video_request = GenerationRequest(
                prompt=params["video_prompt"],
                service_type=AIServiceType.VIDEO_GENERATION,
                params={
                    "source_image_url": intermediate_image_url,
                    "duration": params["duration"],
                    "aspect_ratio": params["aspect_ratio"], 
                    "resolution": params["resolution"],
                    "style": params["style"],
                    "image_strength": params["image_strength"],
                    "seed": params["seed"],
                    "generation_type": "image_to_video"
                },
                user_id=user_id
            )
            
            # 执行视频生成
            video_service = ai_service_manager.get_best_service_for_type(AIServiceType.VIDEO_GENERATION)
            if not video_service:
                raise Exception("没有可用的视频生成服务")
                
            video_result = loop.run_until_complete(
                video_service.generate_video(video_request)
            )
            
            if not video_result.success:
                raise Exception(f"视频生成失败: {video_result.error_message}")
                
            video_url = video_result.result_url
            video_cost = video_result.cost or 0.2
            total_cost = image_cost + video_cost
            
            logger.info(f"任务 {task_id} - 视频生成完成: {video_url}")
            
            # 返回最终结果
            result = {
                'success': True,
                'video_url': video_url,
                'intermediate_image_url': intermediate_image_url,
                'image_cost': image_cost,
                'video_cost': video_cost,
                'total_cost': total_cost,
                'message': '模板生视频完成',
                'generation_type': 'template_to_video_combined',
                'aspect_ratio': params['aspect_ratio'],
                'duration': params['duration']
            }
            
            logger.info(f"任务 {task_id} - 组合流程执行成功")
            return result
            
        finally:
            loop.close()
    
    except Exception as e:
        logger.error(f"任务 {task_id} - 执行失败: {str(e)}")
        
        # 更新任务状态为失败
        self.update_state(
            state='FAILURE',
            meta={
                'error': str(e),
                'message': f'模板生视频失败: {str(e)}',
                'success': False
            }
        )
        
        # 重新抛出异常，让Celery正确处理
        raise